﻿using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
using System.Text;

public class HttpClient
{
    private const string sContentType = "application/x-www-form-urlencoded;charset=GBK";

    public static string Send(string data, string url)
    {
        return Send(Encoding.GetEncoding("GBK").GetBytes(data), url);
    }

    public static string Send(byte[] data, string url)
    {
        Stream responseStream;
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        if (request == null)
        {
            throw new ApplicationException(string.Format("Invalid url string: {0}", url));
        }
        // request.UserAgent = sUserAgent;
        request.ContentType = sContentType;
        // request.Headers.Add("charset", "GBK");

        request.Method = "POST";
        request.ContentLength = data.Length;

        Stream requestStream = request.GetRequestStream();
        requestStream.Write(data, 0, data.Length);
        requestStream.Close();
        try
        {
            responseStream = request.GetResponse().GetResponseStream();
        }
        catch (Exception exception)
        {
            throw exception;
        }
        string str = string.Empty;
        using (StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("GBK")))
        {
            str = reader.ReadToEnd();
        }
        responseStream.Close();
        return str;
    }

    /// <summary>
    /// JSON模式请求返回JSON
    /// </summary>
    /// <param name="jObject"></param>
    /// <param name="url"></param>
    /// <returns></returns>
    public static JObject Send(JObject jObject, string url)
    {
        Stream responseStream;
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        if (request == null)
        {
            throw new ApplicationException(string.Format("Invalid url string: {0}", url));
        }
        // request.UserAgent = sUserAgent;
        request.Headers.Add("charset", "utf-8");
        var data = Encoding.UTF8.GetBytes(jObject.ToString());
        request.Method = "POST";
        request.ContentLength = data.Length;
        request.ContentType = "application/json;charset=utf-8";
        Stream requestStream = request.GetRequestStream();
        requestStream.Write(data, 0, data.Length);
        requestStream.Close();
        try
        {
            var response = request.GetResponse();
            responseStream = response.GetResponseStream();
        }
        catch (Exception exception)
        {
            throw;
        }
        string str = string.Empty;
        using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
        {
            str = reader.ReadToEnd();
        }
        responseStream.Close();
        return JObject.Parse(str);
    }
}